
#import "SMAPIClient.h"
#import "SMConstants.h"
#import "SMAuthManager.h"

@implementation SMAPIClient
+ (instancetype)shared {
    static SMAPIClient *client;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ client = [SMAPIClient new]; });
    return client;
}
- (instancetype)init {
    if (self = [super init]) {
        NSURL *baseURL = [NSURL URLWithString:kSMBaseURLString];
        _manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
        _manager.requestSerializer = [AFJSONRequestSerializer serializer];
        _manager.responseSerializer = [AFJSONResponseSerializer serializer];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/plain",@"text/html", nil];
        [self refreshAuthHeader];
    }
    return self;
}
- (void)refreshAuthHeader {
    NSString *token = [[SMAuthManager shared] token];
    if (token.length) {
        [_manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", token] forHTTPHeaderField:@"Authorization"];
    } else {
        [_manager.requestSerializer setValue:nil forHTTPHeaderField:@"Authorization"];
    }
}
- (void)GET:(NSString *)path parameters:(NSDictionary *)params success:(SMAPISuccess)success failure:(SMAPIFailure)failure {
    [self refreshAuthHeader];
    [_manager GET:path parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success) success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (failure) failure(error);
    }];
}
- (void)POST:(NSString *)path parameters:(NSDictionary *)params success:(SMAPISuccess)success failure:(SMAPIFailure)failure {
    [self refreshAuthHeader];
    [_manager POST:path parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success) success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (failure) failure(error);
    }];
}
@end
